package com.nervenets.web.controller.handler.config;

import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.StringUtils;
import org.weixin4j.Configuration;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;
import org.weixin4j.pay.JsApiTicket;
import org.weixin4j.pay.SignUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信页面配置接口
 * Created by Joe on 17-3-26.
 */
public class WxConfigHandler extends Handler<WxConfigParams> {

    @Override
    public String handle(WxConfigParams params, HttpServletRequest request) throws Exception {
        WxConfigModel model = new WxConfigModel();
        final String requestURL = request.getRequestURL().toString();
        model.setAppId(Configuration.getOAuthAppId());
        String nonceStr = StringUtils.randomString(16);
        model.setNonceStr(nonceStr);
        int timestamp = JodaUtils.getTimestamp();
        model.setTimestamp(timestamp);
        if (requestURL.contains("localhost") || requestURL.contains("127.0.0.1")) return successMessage(model);
        final Weixin weixin = Global.getWeixin();
        JsApiTicket jsApi_ticket = null;
        try {
            jsApi_ticket = weixin.getJsApi_Ticket();
        } catch (WeixinException e) {
            if (e.shouldReLogin()) {
                weixinLogin();
                return errorMessage(MessageCode.code_301);
            }
            throw e;
        }
        String signature = SignUtil.getSignature(jsApi_ticket.getTicket(), nonceStr, timestamp + "", params.getUrl());
        System.out.println(params.getUrl());
        model.setSignature(signature);
        return successMessage(model);
    }

    @Override
    public String result() throws Exception {
        return null;
    }
}
